package com.test.manage;

import com.test.pojo.DataEntity;
import com.test.runable.Task1;
import com.test.runable.Task2;
import com.test.runable.Task3;
import com.test.util.PropertiesUtil;

import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 线程管理调度器
 */
public class ThreadManager {
    private static ExecutorService executorService1;
    private static ExecutorService executorService2;
    private static ExecutorService executorService3;

    private static ConcurrentLinkedQueue<DataEntity> queue1 = new ConcurrentLinkedQueue<>();
    private static ConcurrentLinkedQueue<DataEntity> queue2 = new ConcurrentLinkedQueue<>();
    private static ConcurrentLinkedQueue<DataEntity> queue3 = new ConcurrentLinkedQueue<>();

    public static void offerQueue(final DataEntity entity) {
        int queueNo = entity.getState().getCode();
        switch (queueNo) {
            case 1:
                queue1.offer(entity);
                break;
            case 2:
                queue2.offer(entity);
                break;
            case 3:
                queue3.offer(entity);
                break;
            case 4:
                System.out.println("DataEntity is done: " + entity);
                break;
            default:
                break;
        }
    }

    /**
     * 构造起始数据
     */
    public static void buildInitData() {
        for (int i = 0; i < 100; i++) {
            DataEntity entity = new DataEntity();
            queue1.offer(entity);
        }
    }

    /**
     * 开始处理，启动处理线程
     */
    public static void start() {
        int count1 = Integer.valueOf(PropertiesUtil.getProperty("thread.count1"));
        executorService1 = Executors.newFixedThreadPool(count1);
        for (int i = 0; i < count1; i++) {
            executorService1.execute(new Task1(queue1));
        }
        executorService1.shutdown();

        int count2 = Integer.valueOf(PropertiesUtil.getProperty("thread.count2"));
        executorService2 = Executors.newFixedThreadPool(count2);
        for (int i = 0; i < count2; i++) {
            executorService2.execute(new Task2(queue2));
        }
        executorService2.shutdown();

        int count3 = Integer.valueOf(PropertiesUtil.getProperty("thread.count3"));
        executorService3 = Executors.newFixedThreadPool(count3);
        for (int i = 0; i < count2; i++) {
            executorService3.execute(new Task3(queue3));
        }
        executorService3.shutdown();
    }
}
